/*
 * Copyright 2013-2014 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.web.freemark.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.common.utils.DateUtil;
import com.xdtech.common.utils.DateUtil.DateStyle;
import com.xdtech.core.init.InitCacheData;
import com.xdtech.core.orm.utils.BeanUtils;
import com.xdtech.web.model.ComboBox;
import com.xdtech.web.model.ResultMessage;

/**
 * 
 * @author max.zheng
 * @create 2014-10-12下午8:30:15
 * @since 1.0
 * @see
 */
@Component
@RequestMapping("/common.do")
public class CommonController {
	
	@RequestMapping(params = "skipPage")
	public ModelAndView skip(String skipPage) {
		skipPage = skipPage.replaceAll("_", "/");
		return new ModelAndView(skipPage+"_ftl");
	}
	
	@RequestMapping(params = "loadComboBox")
	@ResponseBody
	public Object loadComboBox(String key,String value,String text,String isSearch) {
		List items = InitCacheData.dictionary.get(key);
		List<ComboBox> comboBoxs = BeanUtils.copyListProperties(ComboBox.class, items);
		if ("true".equals(isSearch)) {
			comboBoxs.add(0,new ComboBox("", "------", false));
		}
		for (ComboBox comboBox : comboBoxs) {
			if ((StringUtils.isNotBlank(value)&&value.contains(comboBox.getValue()))
					||(StringUtils.isNotBlank(text)&&text.contains(comboBox.getName()))) {
				comboBox.setSelected(true);
			}
		}
		return comboBoxs;
	}
	
	/**
	 * 加载下拉框，该下拉框显示值text和value是一致的都是采用text，解决查询时无法获取text问题；
	 * 
	 * @author max.zheng
	 * @create 2015-4-18下午5:52:07
	 * @modified by
	 * @param key
	 * @return
	 */
	@RequestMapping(params = "loadComboBoxText")
	@ResponseBody
	public Object loadComboBoxText(String key) {
		List items = InitCacheData.dictionary.get(key);
		List<ComboBox> comboBoxs = BeanUtils.copyListProperties(ComboBox.class, items);
		//用来设置下拉框的value和text成一直，主要解决在查询收集条件的时候，获取的查询时是value里，但是后台是保存text，
		//因为表单验证的时候是传text，导致两者不统一，扩展后台转换方法，方便设置获取； add by max 20150418
		List<ComboBox> comboBoxsTemp = new ArrayList<ComboBox>();
		for (ComboBox comboBox : comboBoxs) {
			comboBoxsTemp.add(new ComboBox(comboBox.getName(), comboBox.getName(), false));
		}
		return comboBoxsTemp;
	}

	
	@ResponseBody
	@RequestMapping(params = "uploadFile")
	public ResultMessage uploadFile(HttpServletRequest request,
			@RequestParam("filedata") MultipartFile file) throws Exception {
		List<String> filePathList = new ArrayList<String>();
		ResultMessage rs = new ResultMessage();
		try {
			String rootUrl = ApplicationContextUtil.getWebappUrl();
			String filePath = "uploadFile/"+DateUtil.dateToString(new Date(), DateStyle.YYYYMMDD);
			String uploadDir = request.getRealPath("/"+filePath);
			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			int indexFile = file.getOriginalFilename().lastIndexOf(".");
			String createFileName = request.getParameter("fileName");
			String fileName;
			if ("self".equals(createFileName)) {
				//根据用户定义的文件名称保存
				fileName = file.getOriginalFilename();
			} else {
				//系统自创建
				fileName = System.currentTimeMillis()+"_"+RandomStringUtils.random(4, "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")+file.getOriginalFilename().substring(indexFile, file.getOriginalFilename().length());
			}
//			System.out.println(file.getContentType());
			String imgUrl = filePath+"/"+fileName;
			filePath = uploadDir + "/"+fileName;
			file.transferTo(new File(filePath));
//			filePathList.add(imgUrl);
			rs.setObj(imgUrl);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	@ResponseBody
	@RequestMapping(params = "deleteFile")
	public ResultMessage deleteFile(HttpServletRequest request,String path) throws Exception {
		ResultMessage rs = new ResultMessage();
		try {
			if (StringUtils.isNotBlank(path)) {
				String filePath = request.getRealPath("/"+path);
				File file = new File(filePath);
				if (file.exists()) {
					file.delete();
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
}
